package com.example.test.async.anotherWay;

import cn.hutool.core.io.FileUtil;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class MyServiceImpl implements MyService{
    private RestTemplate restTemplate;
    private String token;

    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @PostConstruct
    public void init() {
        restTemplate = new RestTemplateBuilder().build();
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            /**
             * 设置RestTemplate自带的异常处理器不做异常处理
             **/
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
            }
        });

        token = login();
    }

    /**
     * 登录
     **/
    private String login() {
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("username","wangbo");
        param.add("password", Base64.getEncoder().encode("123456".getBytes(StandardCharsets.UTF_8)));

        String url = String.format("http://%s:%s/service/api/%s", "192.168.88.245", "8080", "user/login");
        String result = restTemplate.postForObject(url, param, String.class);
        return result;
    }


    @Override
    public void recognize(File file) {
        search(file);
    }

    /**
     * 识别
     **/
    private String search(File file) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", token);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        String url = String.format("http://%s:%s/service/api/%s", "192.168.88.245", "8080", "search");
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        String str = Base64.getEncoder().encodeToString(FileUtil.readBytes(file));
        param.add("image-data", "data:image/jpeg;base64," + str);
        param.add("calibrated-threshold", 50);
        param.add("tops", 1);

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        String result = restTemplate.postForObject(url, httpEntity, String.class);
        return result;
    }
}
